package com.youyun56.gps.android.service;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

import com.youyun56.gps.android.RunStep;
import com.youyun56.gps.android.broadcast.CloseSystemDialogBroadCast;
import com.youyun56.gps.android.common.NetWorkUtil;
import com.youyun56.gps.android.http.HttpManager;
import com.youyun56.gps.android.pojo.Car;
import com.youyun56.gps.android.pojo.Im;

public class LocationUploadService extends Service {
    private RunStep                      runStep        = RunStep.NONE;
    private MyBinder                     binder         = new MyBinder();
    private final static String          tag            = LocationUploadService.class.getName();
    // public final static String url =
    // "http://10.0.2.2/android/android.android.htm";
    public final static String           url            = "http://youyun56.com/android/android.android.htm";
    private SharedPreferences            preference;
    public final static int              gpsUpload      = 4;
    private final List<Im>               ims            = new ArrayList<Im>();
    private Car                          car;
    private int                          goodIndex;
    public final static String           charset        = "UTF-8";
    public final static String           line           = System.getProperty("line.separator");
    private CloseSystemDialogBroadCast   bc             = new CloseSystemDialogBroadCast();
    private static LocationUploadService service;
    private AlarmManager                 alarms;
    private PendingIntent                pendingIntent;
    private WakeLock                     wakeLock;
    private Long                         uploadInterval = 60 * 15L;
    
    public static LocationUploadService getInstance() {
        return service;
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.i(tag, "onStart");
        if (!NetWorkUtil.isGprsOpen(this)) {
            NetWorkUtil.openGprs(this, true);
        }
    }
    
    @Override
    public void onCreate() {
        try {
            Log.i(tag, "LocationUploadService onCreate");
            super.onCreate();
            Context ctx = getApplicationContext();
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            if (prefs != null) {
                setPreference(prefs);
            }
            car = new Car(prefs.getLong("id", 0));
            service = this;
            if (car.getId() != 0) {
                startGps(uploadInterval);
            }
            if (!NetWorkUtil.isGprsOpen(this)) {
                NetWorkUtil.openGprs(this, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(tag, e.getMessage(), e);
        }
        
    }
    
    public void regBroadCase() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(bc, filter);
    }
    
    public void unRegBroadCase() {
        unregisterReceiver(bc);
    }
    
    public Boolean startGps(Long uploadInterval) {
        Log.i(tag, "start gps");
        if (uploadInterval != null) {
            this.uploadInterval = uploadInterval;
        }
        // this.uploadInterval = (long) (60 * 5);
        alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, UploadLocationService.class);
        intent.putExtra("id", car.getId());
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarms.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), this.uploadInterval * 1000, pendingIntent);
        return true;
        
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(tag, "bind");
        return binder;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(tag, "onUnbind");
        return super.onUnbind(intent);
    }
    
    public Boolean acquireWakeLock() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        Boolean screenOn = pm.isScreenOn();
        Log.i(tag, "screen is " + screenOn);
        wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, tag);
        wakeLock.acquire();
        while (!pm.isScreenOn()) {
            try {
                
                Thread.sleep(10);
            } catch (InterruptedException e) {
                Log.e(tag, e.getMessage(), e);
            }
        }
        Log.i(tag, "acuire lock");
        return screenOn;
    }
    
    public void onDestroy() {
        Log.i(tag, "destroy and remove handler");
        runStep = RunStep.NONE;
        if (alarms != null) {
            alarms.cancel(pendingIntent);
        }
        releaseWakeLock();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    
    public void releaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
            Log.i(tag, "release lock");
        }
    }
    
    public class MyBinder extends Binder {
        public LocationUploadService getService() {
            return LocationUploadService.this;
        }
    }
    
    public void setBinder(MyBinder binder) {
        this.binder = binder;
    }
    
    public SharedPreferences getPreference() {
        return preference;
    }
    
    public void setPreference(SharedPreferences preference) {
        this.preference = preference;
    }
    
    public List<Im> getIms() {
        return ims;
    }
    
    public void setCar(Car car) {
        this.car = car;
    }
    
    public Car getCar() {
        return car;
    }
    
    public RunStep getRunStep() {
        return runStep;
    }
    
    public void setRunStep(RunStep runStep) {
        this.runStep = runStep;
    }
    
    public int getGoodIndex() {
        return goodIndex;
    }
    
    public void setGoodIndex(int goodIndex) {
        this.goodIndex = goodIndex;
    }
    
    public LocationManager createLocationManager() {
        return (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    
    public void write(String cmd) {
        // TODO Auto-generated method stub
        HttpManager.getInstance().excutePost(cmd, null);
    }
    
}
